package com.hospital.wx.service.Impl;

import cn.hutool.core.map.MapUtil;
import com.hospital.wx.dao.CommentsDao;
import com.hospital.wx.dao.LikesDao;
import com.hospital.wx.dao.RepliesDao;
import com.hospital.wx.pojo.Comments;
import com.hospital.wx.service.CommentsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class CommentsServiceImpl implements CommentsService {

    @Autowired
    private CommentsDao commentsDao;

    @Autowired
    private RepliesDao repliesDao;

    @Autowired
    private LikesDao likesDao;

    /**
     * 获取文章评论列表，包含评论的基本信息和回复数量
     * @param param 包含postId, offset, limit等参数
     * @return 评论列表
     */
    @Override
    public Map<String, Object> getCommentsByPostId(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();

        Integer postId = MapUtil.getInt(param, "postId");
        Integer offset = MapUtil.getInt(param, "offset", 0);
        Integer limit = MapUtil.getInt(param, "limit", 10);

        // 获取评论总数
        long count = commentsDao.selectCountCommentsByPostId(postId);

        if (count == 0) {
            result.put("comments", new ArrayList<>());
            result.put("total", 0);
            result.put("hasMore", false);
            return result;
        }

        // 获取分页评论
        List<HashMap<String, Object>> comments = commentsDao.getCommentsByPostId(param);

        // 获取当前用户ID（如果已登录）
        Integer patientUserId = MapUtil.getInt(param, "userId", null);

        // 如果用户已登录，批量获取用户点赞的评论ID列表
        Set<Integer> userLikedCommentIds = new HashSet<>();
        if (patientUserId != null) {
            List<Integer> likedIds = likesDao.getUserLikedIds(patientUserId, "comment");
            userLikedCommentIds.addAll(likedIds);
        }

        // 获取每条评论的回复数量和点赞信息
        for (HashMap<String, Object> comment : comments) {
            Integer commentId = (Integer) comment.get("id");

            // 获取回复数量
            long replyCount = repliesDao.selectCountRepliesByCommentId(commentId);
            comment.put("replyCount", replyCount);

            // 获取点赞数量 (使用target_id和target_type)
            long likeCount = likesDao.countLikes(commentId, "comment");
            comment.put("likeCount", likeCount);

            // 判断用户是否已点赞 (使用新的点赞表结构)
            if (patientUserId != null) {
                // 使用已获取的点赞ID集合进行判断，避免多次数据库查询
                boolean isLiked = userLikedCommentIds.contains(commentId);
                comment.put("isLiked", isLiked);
            } else {
                comment.put("isLiked", false);
            }

            // 获取部分回复(例如前3条)
            if (replyCount > 0) {
                Map<String, Object> replyParam = new HashMap<>();
                replyParam.put("commentId", commentId);
                replyParam.put("offset", 0);
                replyParam.put("limit", 10); // 只获取前10条回复
                List<HashMap<String, Object>> replies = repliesDao.getRepliesByCommentId(replyParam);

                // 处理回复的点赞信息
                if (patientUserId != null) {
                    // 批量获取用户点赞的回复ID列表
                    List<Integer> likedReplyIds = likesDao.getUserLikedIds(patientUserId, "reply");
                    Set<Integer> userLikedReplyIdsSet = new HashSet<>(likedReplyIds);

                    // 为每条回复添加点赞信息
                    for (HashMap<String, Object> reply : replies) {
                        Integer replyId = (Integer) reply.get("id");

                        // 获取回复的点赞数(使用target_id和target_type)
                        long replyLikeCount = likesDao.countLikes(replyId, "reply");
                        reply.put("likeCount", replyLikeCount);

                        // 判断用户是否点赞了该回复
                        boolean isReplyLiked = userLikedReplyIdsSet.contains(replyId);
                        reply.put("isLiked", isReplyLiked);
                    }
                } else {
                    // 用户未登录，为每条回复添加默认点赞信息
                    for (HashMap<String, Object> reply : replies) {
                        Integer replyId = (Integer) reply.get("id");

                        // 获取回复的点赞数(使用target_id和target_type)
                        long replyLikeCount = likesDao.countLikes(replyId, "reply");
                        reply.put("likeCount", replyLikeCount);
                        reply.put("isLiked", false);
                    }
                }

                comment.put("topReplies", replies);
            } else {
                comment.put("topReplies", new ArrayList<>());
            }
        }

        // 构建返回结果
        result.put("comments", comments);
        result.put("total", count);
        result.put("hasMore", offset + limit < count);

        return result;
    }


    @Override
    @Transactional
    public int addComment(Comments comments) {
        return commentsDao.addComment(comments);
    }

    @Override
    @Transactional
    public int deleteComment(Map param) {
        //删除该评论的所有回复
        Integer commentId = MapUtil.getInt(param, "id");
        int rows = repliesDao.deleteByCommentId(commentId);
        if (rows < 0) {
            log.error("删除该评论相关回复失败");
            return 0;
        }

        //删除该评论的点赞
        HashMap<String, Object> map = new HashMap<>();
        map.put("targetId", commentId);
        map.put("patientUserId", MapUtil.getInt(param, "patientUserId"));
        rows = likesDao.deleteLike(map);
        if (rows < 0) {
            log.error("删除该评论点赞数失败");
            return 0;
        }

        //删除该评论
        rows = commentsDao.deleteComment(commentId);
        if (rows != 1) {
            log.error("删除该评论失败");
            return 0;
        }
        return rows;
    }
}
